<template>
  <div class="flex-column">
    <div class="flex justify-between flex-row-reverse">
      <div class="text-right flex justify-end flex-wrap align-center">
        <!-- 区域选择 -->
        <region-cascader
          style="width: 300px"
          class="mb-10"
          :multiple="true"
          @change="regionChange"
        />
        <el-select
          v-model="queryData.nodeType"
          clearable
          style="width: 200px"
          class="ml-10 mb-10"
          :placeholder="$t('PLEASE_SELECT') + $t('NODE_TYPE')"
        >
          <el-option
            v-for="item in allNodeTypes"
            :key="item.id"
            :value="item.code"
            :label="item.label"
          />
        </el-select>
        <!-- 录入时间 -->
        <el-date-picker
          v-model="rangeDate"
          class="ml-10 mb-10"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="-"
          :start-placeholder="$t('START_TIME')"
          :end-placeholder="$t('END_TIME')"
          align="right"
          style="width: 300px"
        />
        <el-input
          v-model.trim="queryData.keyword"
          style="width: 200px"
          class="ml-10 mb-10"
          maxlength="32"
          clearable
          :placeholder="$t('NODE_NAME') + '/' + $t('DEVICE_CODE') + '/' + $t('RESOURCE_CODE')"
          @keyup.enter.native="$debounce(search)"
        />
        <el-checkbox v-model="queryData.freeNode" class="ml-10 mb-10">{{
          $t('ONLY_NOT_OWNED')
        }}</el-checkbox>
        <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">
          {{ $t('QUERY') }}
        </el-button>
      </div>
      <div class="flex mb-10">
        <el-button v-if="permission.addBtn" type="primary" icon="el-icon-plus" @click="add">{{
          $t('ADD_NODE')
        }}</el-button>
        <el-button
          v-if="permission.import"
          type="primary"
          icon="el-icon-upload2"
          @click="importVisible = true"
        >{{ $t('IMPORT') }}</el-button>
        <!-- <el-button
          type="primary"
          icon="el-icon-download"
          @click="exportClick"
        >{{ $t('EXPORT') }}</el-button> -->
      </div>
    </div>
    <TableView
      v-loading="loading"
      :table-header="tableHeader"
      :table-data="tableData"
      :page-data="pageData"
      :operate-width="160"
      @sortChange="sortChange"
      @operate="operate"
      @pageChange="pageChange"
    />
    <!-- 新增、编辑组件 -->
    <edit :visible="editShow" :type="operateType" :row-data="rowData" @close="close" />
    <!-- 节点列表组件 -->
    <edit-ports v-if="portIng" :visible="portIng" :row-data="rowData" @close="close" />
    <!--导入引导-->
    <ConfImportDialog
      :visible="importVisible"
      template-url="template/节点批量导入模板.zip"
      import-url="/import/importNode"
      service-name="oen"
      import-tips="NODE_IMPORT_TIPS"
      @close="close"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import nodeApi from '@/api/oen/NodeApi'
  import clusterApi from '@/api/afs/ClusterApi'
  import { downloadFile, deepClone, pickerOptionsClassMonth, getParentsById } from '@/utils/common'
  import Edit from './Edit'
  import RegionCascader from '@/components/RegionCascader'
  import EditPorts from './components/EditPorts'
  import TableView from '@/components/TableView'
  import ConfImportDialog from '@/components/ConfImportDialog'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    name: 'ConfNodePage',
    components: {
      Edit,
      RegionCascader,
      EditPorts,
      TableView,
      ConfImportDialog
    },
    data() {
      return {
        portIng: false,
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        rangeDate: null,
        queryData: {
          stationIdList: [],
          startTime: '',
          endTime: '',
          nodeType: '',
          keyword: '',
          freeNode: false
        },
        pickerOptions: pickerOptionsClassMonth(this),
        tableData: [],
        rowData: {},
        operateType: 'add',
        editShow: false,
        sortData: {
          field: null,
          type: null
        },
        tableHeader: [
          {
            label: 'NODE_NAME',
            prop: 'nodeName',
            width: 250,
            fixed: 'left',
            configType: 'default'
          },
          {
            label: 'BELONGS_REGION_STATION_NAME',
            prop: 'stationName',
            width: 250
          },
          {
            label: 'BELONGS_ROOM_NAME',
            prop: 'roomName',
            width: 250
          },
          {
            label: 'NODE_TYPE',
            prop: 'nodeTypeName',
            width: 140
          },
          {
            label: 'NODE_MODEL',
            prop: 'model',
            width: 160
          },
          {
            label: 'DEVICE_CODE',
            prop: 'deviceCode',
            width: 160
          },
          {
            label: 'RESOURCE_CODE',
            prop: 'resourceCode',
            configType: 'extend'
          },
          {
            label: 'VENDOR',
            prop: 'company',
            width: 145,
            configType: 'extend'
          },
          {
            label: 'INPUT_TIME',
            prop: 'createTime',
            width: 165
          }
        ],
        importVisible: false,
        loading: false
      }
    },
    computed: {
      ...mapGetters(['dictMap', 'allNodeTypes', 'baseRegionList', 'stationTree']),
      permission() {
        return this.$store.getters.getAuthData('conf:node')
      }
    },
    activated() {
      this.loadData()
      // this.add()
    },
    methods: {
      sortChange(data) {
        this.sortData = data
        this.loadData()
      },
      loadData() {
        const queryData = {
          ...{ page: this.pageData },
          ...searchData
        }
        nodeApi.queryPage(queryData).then(res => {
          const list = res.list || []
          list.forEach(i => {
            i.stationName = this.getRegionStationName(i.stationId)
            i.roomName = this.getRegionName(i.roomId)
            i.nodeTypeName = this.getDeviceTypeName(i.nodeType)
            i.deviceCode = i.nodeCategory === 'AFS' ? i.nodeId : ''
            i.btns = this.getBtns(i).filter(j => {
              // 如果是接头盒直通就不现实设备端口按钮
              if (
                i.nodeCategory === 'SPLICE_CLOSURE' &&
                i.properties.spliceClosure.connectionModeType === 'DIRECT_CONNECTION'
              ) {
                return j.key !== 'view'
              }
              return j
            })
          })
          this.tableData = list
          this.pageData.total = res.total
        })
      },
      getBtns() {
        const btns = [
          {
            key: 'view',
            show: this.permission.port,
            label: 'DEVICE_PORT'
          },
          {
            key: 'mod',
            show: this.permission.mod,
            label: 'MOD'
          },
          {
            key: 'del',
            show: this.permission.del,
            label: 'DEL'
          }
        ]
        return btns.filter(i => i.show)
      },
      // 获取设备类型
      getDeviceTypeName(deviceType) {
        return this.dictMap.NODE_TYPE ? this.dictMap.NODE_TYPE[deviceType] : ''
      },
      // 获取区域/站点/机房
      getRegionName(regionId) {
        const stationData = this.baseRegionList.find(i => i.regionId === regionId)
        return stationData ? stationData.regionName : ''
      },
      getRegionStationName(regionId) {
        const parents = getParentsById(this.stationTree, regionId, 'regionId') || []
        return parents
          .reverse()
          .map(i => i.regionName)
          .join('/')
      },
      // 区域搜索条件改变
      regionChange(data) {
        this.queryData.stationIdList = data
      },
      // 关键字搜索
      search() {
        this.pageData.page = 1
        const timeData = this.rangeDate
          ? { startTime: this.rangeDate[0], endTime: this.rangeDate[1] }
          : {}
        this.queryData.keyword = this.queryData.keyword.trim()
        searchData = {
          ...this.queryData,
          ...timeData,
          sort: this.sortData.type ? this.sortData : null
        }
        searchData.nodeType = searchData.nodeType || null
        if (searchData.stationIdList.length === 0) {
          delete searchData.stationIdList
        }
        this.loadData()
      },
      // 操作
      operate(data) {
        switch (data.type) {
        case 'view':
          this.showPorts(data.data)
          break
        case 'mod':
          this.operateType = 'mod'
          this.rowData = data.data
          this.editShow = true
          break
        case 'del':
          this.del(data.data)
          break
        }
      },
      // 顶部添加
      add() {
        this.operateType = 'add'
        this.rowData = {}
        this.editShow = true
      },
      // 删除
      del(row) {
        this.$confirm(this.$t('CONFIRM_DELETION_PROMPT_TIP', { key: this.$t('NETWORK_NODE'), value: row.nodeName }), {
          type: 'warning'
        })
          .then(() => {
            nodeApi
              .delByNodeId({
                nodeId: row.nodeId,
                nodeName: row.nodeName
              })
              .then(res => {
                if (res) {
                  this.$message.success(this.$t('DELETE_SUCCESS'))
                  this.loadData(true)
                }
              })
          })
          .catch(() => {})
      },
      // 展开节点弹窗
      showPorts(row) {
        if (row.nodeCategory === 'TRANSPORT') {
          nodeApi.transPortInfo({ nodeId: row.nodeId }).then(res => {
            if (res) {
              row.properties.trans.shelfList = res
              this.rowData = deepClone(row)
              this.portIng = true
              console.log('this.rowData', this.rowData)
            }
          })
        } else if (row.nodeCategory === 'AFS') {
          if (row.nodeType !== 'CLUSTER') {
            nodeApi.portList({ nodeId: row.nodeId }).then(res => {
              this.getAfsPort(row, res || [])
            })
          } else {
            // 集群
            this.loading = true
            clusterApi.clusterExtPort({ clusterId: row.nodeId }).then((res = []) => {
              let portList = []
              res.devices.forEach(i => {
                const ports = i.ports.map(j => {
                  const partFlag =
                    i.cabinetName +
                    '-' +
                    i.deviceName +
                    '-' +
                    j.partFlag.replace('M', 'B') +
                    this.$t('FACE')
                  return {
                    ...j,
                    partFlag: partFlag
                  }
                })
                portList = [...portList, ...ports]
              })
              console.log(portList, 'portList')
              this.getAfsPort(row, portList)
            })
          }
        } else if (row.nodeCategory === 'LIGHT_SPLIT') {
          nodeApi
            .portList({
              nodeId: row.nodeId,
              status: null
            })
            .then(res => {
              row.properties.split.inPortName = this.$utils.handleServiceI18n(res[0].bizName)
              this.rowData = deepClone(row)
              this.portIng = true
            })
        } else {
          this.rowData = deepClone(row)
          this.portIng = true
          console.log('this.rowData', this.rowData)
        }
      },
      getAfsPort(row, res) {
        res = res || []
        // 数据组装成数结构
        const portTree = []
        res.forEach(i => {
          const portItem = {
            bizName: this.$utils.handleServiceI18n(i.bizName),
            portName: this.$utils.handleServiceI18n(i.portName),
            portId: i.portId
          }
          const partId = i.deviceId + i.partFlag
          // 查询已有树结构里面是否有当前面
          const faceData = portTree.find(j => j.partId === partId)
          if (faceData) {
            faceData.portList.push(portItem)
          } else {
            portTree.push({
              partId: partId,
              faceName: i.partFlag,
              portList: [portItem]
            })
          }
        })
        console.log('portTree', portTree)
        row.properties.afsInfo = { faceList: portTree }
        this.rowData = deepClone(row)
        this.portIng = true
        console.log('this.rowData', this.rowData)
        this.loading = false
      },
      // 弹窗关闭
      close(load) {
        this.portIng = false
        this.editShow = false
        this.importVisible = false
        if (load === true) {
          this.loadData()
        }
      },
      // 导出文件
      exportClick() {
        const timeData = this.rangeDate
          ? { startTime: this.rangeDate[0], endTime: this.rangeDate[1] }
          : {}
        const queryData = {
          ...this.queryData,
          ...{ page: this.pageData },
          ...timeData
        }
        nodeApi.expData(queryData).then(res => {
          downloadFile(res, `${this.$t('NODE_EXPORT_DATA')}.xlsx`)
        })
      },
      pageChange(data) {
        this.pageData = data
        this.loadData()
      }
    }
  }
</script>

<style></style>
